package com.test;

/**
 *
 * 线程同步
 *
 */

public class demo2  implements Runnable {
    private String name;
    private Object prev;
    private Object self;

    public demo2(String name, Object prev, Object self) {
        this.name = name;
        this.prev = prev;
        this.self = self;
    }

    @Override
    public void run() {
        int count = 10;
        while (count > 0) {
            //
            synchronized (prev) {
                //System.out.println("-jjj- ");
                /**
                 * 第一次，prev=c,self=a
                 * 对a进行释放 将c存入缓冲队列，
                 * prev=a,self=b对b进行释放 将a存入缓冲队列，
                 * prev=b,self=c对c进行释放 将b存入缓冲队列，
                 * 第一轮，count=10;
                 * 缓存队列中a，b
                 *
                 * 在第二轮中
                 * 对象c可以在缓冲队列中得到，不会阻塞
                 * 故三个线程会一次执行不会中断，直到count<0
                 *
                 * b释放，a缓存
                 *p-b，celf-  c
                 * 第二次
                 * b释放
                 *
                 */
                synchronized (self) {
                    System.out.print(name);
                    count--;
                    self.notify();
                }

                try {
                    prev.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        demo2 aThread = new demo2("a", c, a);
        demo2 bThread = new demo2("b", a, b);//cba abc bca acb cab
        demo2 cThread = new demo2("c", b, c);
        new Thread(aThread).start();
     //   Thread.sleep(10);
        new Thread(bThread).start();
        //Thread.sleep(10);
        new Thread(cThread).start();
        //Thread.sleep(10);

    }
}